package pay

import (
	"OnlineRetailers/models/Admin"
	USER "OnlineRetailers/models/User"
	"fmt"
	"github.com/astaxie/beego/orm"
	"math/rand"
	"strconv"
	"time"
)

func postOrder(order *USER.Order) error {
	o := orm.NewOrm()
	var err error
	order.Time = time.Now().Unix()
	s := strconv.FormatInt(time.Now().Unix(), 10)
	order.OrderId = "ORD" + s + fmt.Sprintf("%08v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(100000000))
	order.State = 1
	if order.Coupon == nil {
		order.Coupon = &Admin.Coupon{CouponId: "0"}
	}
	//fmt.Println(order.User)
	_, err = o.Insert(order)
	if err != nil {
		fmt.Println("InsertOrder")
		return err
	}
	s = strconv.FormatInt(time.Now().Unix(), 10)
	for _, orderCart := range order.OrderCart {
		orderCart.OrderCartCartId = "ORD" + s + fmt.Sprintf("%08v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(100000000))
		_, err := o.Insert(orderCart)
		if err != nil {
			fmt.Println("InsertorderCart")

			return err
		}
		//s=strconv.FormatInt(time.Now().Unix(), 10)
		//id:="OOC" +s+ fmt.Sprintf("%08v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(100000000))
		sql := "insert into  `order_order_carts` (`order_id`,`order_cart_id`) values (?,?)"
		exc, err := o.Raw(sql, order.OrderId, orderCart.OrderCartCartId).Exec()
		if err != nil {
			fmt.Println("insert_order_order_carts")
			return err
		}
		num, err := exc.RowsAffected()
		if err != nil {
			return err
		} else if num == 0 {
			return fmt.Errorf(" num==0")
		}
	}
	return nil

}
